﻿#region "Copyright (C) Lenny Granovsky. 2011-2013"
//    This library provides extended cache capabilities to the ASP.NET applications.
//
//                Copyright (C) Lenny Granovsky. 2011-2013. 
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//    This program comes with ABSOLUTELY NO WARRANTY.
//    This is free software, and you are welcome to redistribute it
//    under certain conditions;
#endregion

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Threading;

namespace FlexiCache
{
    /// <summary>
    /// Class provides object collection functionality for session on demand data.
    /// This class is not intended to be used directly. The RuntimeContext should be used instead.
    /// </summary>
    public class SessionOnDemandController : ISessionOnDemandController
    {
        private const string ApplicationContextSessionOnDemandStorageMemorySlotName = "RuntimeContextApplicationSessionOnDemandStorage";
        private const string HttpContextSlotName = "SessionOnDemandController";
        /// <summary>
        /// Collection of changes.
        /// </summary>
        private List<string> Changes { get; set; }
        /// <summary>
        /// Collection of items.
        /// </summary>
        private System.Collections.Generic.Dictionary<string, object> DataCollection { get; set; }
        protected SessionOnDemandProvider StorageProvider;

        /// <summary>
        /// Gets an instance of Session on Demand controller associated with current request and its handler.
        /// </summary>
        public static SessionOnDemandController Current
        {
            get
            {
                if (System.Web.HttpContext.Current == null)
                {
                    LocalDataStoreSlot slot = Thread.GetNamedDataSlot(ApplicationContextSessionOnDemandStorageMemorySlotName);
                    object tmp = Thread.GetData(slot);
                    if (tmp != null)
                        return (SessionOnDemandController)tmp;
                    Thread.SetData(slot, new SessionOnDemandController());
                    tmp = Thread.GetData(slot);
                    if (tmp != null)
                        return (SessionOnDemandController)tmp;
                    throw new Exception("Unable to initialize SessionOnDemandController in thread memory data slot.");
                }
                if (System.Web.HttpContext.Current.Items[HttpContextSlotName] == null)
                    CreateInstance(CachingConfiguration.Current.SessionOnDemandConfig.IsEnabled);
                return (SessionOnDemandController)System.Web.HttpContext.Current.Items[HttpContextSlotName];
            }
        }

        /// <summary>
        /// Deafult constructor.
        /// </summary>
        private SessionOnDemandController()
        {
            this.InitStorageProvider();
            this.Changes = new List<string>();
            this.DataCollection = new Dictionary<string, object>();
        }

        private void InitStorageProvider()
        {
            this.StorageProvider = new SessionOnDemandProvider();
        }

        /// <summary>
        /// Method adds data into session on demand storage with specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="value">Data to store.</param>
        public void Add(string key, object value)
        {
            this.Set(key, value);
        }

        /// <summary>
        /// Method clears all items in the session on demand storage.
        /// </summary>
        public void Clear()
        {
            this.StorageProvider.Clear();
            this.Changes.Clear();
            this.DataCollection.Clear();
        }

        /// <summary>
        /// Method gets a data from the session on demand storage using specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <returns>Returns object from session.</returns>
        public object Get(string key)
        {
            if (this.DataCollection.ContainsKey(key))
                return this.DataCollection[key];
            object tmp = this.StorageProvider.Get(key);
            this.DataCollection.Add(key, tmp);
            return this.DataCollection[key];
        }

        /// <summary>
        /// Method removes an item from the session on demand storage using specified key.
        /// </summary>
        public void Remove(string key)
        {
            if (this.DataCollection.ContainsKey(key))
                this.DataCollection.Remove(key);
            this.TrackChange(key);
        }

        /// <summary>
        /// Method sets data in the session on demand storage with specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="value">Data to store.</param>
        public void Set(string key, object value)
        {
            this.DataCollection[key] = value;
            this.TrackChange(key);
        }

        /// <summary>
        /// Gets or sets data in the session on demand storage with specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        public object this[string key]
        {
            get
            {
                return this.Get(key);
            }
            set
            {
                this.Set(key, value);
            }
        }

        private void TrackChange(string key)
        {
            if (!this.Changes.Contains(key))
                this.Changes.Add(key);
        }

        /// <summary>
        /// Method creates and initializes an instance of Session on Demand controller associated with current request and its handler.
        /// </summary>
        /// <remarks>This method should not be used directly from the application code. This is for internal use by application infrastructure.</remarks>
        /// <param name="isEnabled">Boolean value indicated if session on demand functionality is enabled for the the application.</param>
        public static void CreateInstance(bool isEnabled)
        {
            SessionOnDemandController controller = new SessionOnDemandController();
            if (System.Web.HttpContext.Current != null)
            {
                if (System.Web.HttpContext.Current.Session != null)
                {
                    controller.StorageProvider.AspNetAppId = FlexiCache.Utilities.ApplicationIdentification.CurrentApplicationId;
                    controller.StorageProvider.AspNetSessionId = System.Web.HttpContext.Current.Session.SessionID;
                    //use SessionTimeout + special flexibility interval to assure we don't clear session data too early.
                    controller.StorageProvider.SessionTimeout = System.Web.HttpContext.Current.Session.Timeout + CachingConfiguration.SessionOnDemandRenewFlexibilityInterval;
                    controller.StorageProvider.IsEnabled = isEnabled;
                }
                System.Web.HttpContext.Current.Items[HttpContextSlotName] = controller;
            }
        }

        /// <summary>
        /// Method synchronizes the data with Session on Demand external storage.
        /// </summary>
        /// <remarks>This method should not be used directly from the application code. This is for internal use by application infrastructure.</remarks>
        public void SyncWithStorage()
        {
            //save changes
            if (this.Changes.Count > 0)
            {
                //remove all items that were updated set to NULL.
                foreach (string key in this.Changes)
                {
                    if (!this.DataCollection.ContainsKey(key))
                        this.StorageProvider.Remove(key);
                }
                this.Changes.Clear();
            }
            //update all items that were demanded because they can have internal changes.
            foreach (string key in this.DataCollection.Keys)
                this.StorageProvider.Set(key, this.DataCollection[key]);
        }

        /// <summary>
        /// Method updates the expiration date and time for specified item to renew it for next session timeout interval.
        /// </summary>
        /// <remarks>This method should not be used directly from the application code. This is for internal use by application infrastructure.</remarks>
        public void Renew()
        {
            this.StorageProvider.Renew();
        }
    }
}
